<template>
  <view style="height: 100vh;">
    <!-- <view style="background-color: #fff;width: 100%;text-align:center;padding: 15rpx 0;position: fixed;top: 0;z-index: 999;">
      <picker mode="selector"
              @change="bindPickerChange"
              :value="index"
              :range="selectorObj"
              range-key="name">
        <view class="uni-input">{{selectorObj[index].name||'请选择'}}
        </view>
      </picker>
    </view> -->
    <view class="s-body chat-con">
      <view @click="isShow = false">
        <scroll-view class="maxh"
                     v-if="historyTextList && historyTextList.length"
                     :scroll-y="true"
                     :scroll-top="scrollY">
          <chat-list :historyTextList="historyTextList"
                     :loading="loading"
                     :AiModel="AiModel"
                     type="chat"
                     @refsh="refsh"></chat-list>

        </scroll-view>
        <view v-else
              class="zl-flex zl-row-center"
              style="width: 630rpx; margin: 200rpx auto 0;">
          <view class="zl-flex-col zl-row-center zl-m-t-20 zl-col-center">
            <image class=""
                   style="width: 80rpx; height: 80rpx;margin-bottom: 40rpx;"
                   :src="AiModel === 1 ? '/static/aiCreate/icon_model_color_01.png' : AiModel === 2 ? '/static/aiCreate/icon_model_color_02.png' : '/static/aiCreate/icon_model_color_03.png'">
            </image>
            <view class="zl-color-333 zl-font-36 zl-m-b-30">嗨！我是{{AiModelName}}</view>
            <view class="zl-color-999 zl-font-30"
                  style="text-align:center">我可以帮你搜索、答疑、写作、请把你的任务交给我吧～</view>
          </view>
        </view>
      </view>
      <view>
        <view>
          <view class="zl-flex zl-row-center zl-m-b-16 zl-p-t-20"
                v-show="isShow">
            <view style="width: 60rpx;height: 10rpx;background: #BDBCBC;border-radius: 8rpx;"></view>
          </view>
          <view class="zl-flex-col"
                v-show="isShow"
                style="width: 100%;background-color: #fff;padding: 20rpx 0;">
            <view v-for="(item, index) in selectorObj"
                  :key="index"
                  class="zl-flex zl-row-between  zl-p-t-22 zl-p-b-22 zl-p-l-30 zl-p-r-30"
                  style="width: 100%"
                  @click="bindPickerChange(item)"
                  :class="['zl-flex zl-row-between', {active: AiModel === item.aiModel}]">
              <view class="zl-flex zl-row-center">
                <image class=""
                       style="width: 44rpx; height: 44rpx;margin-right: 24rpx;"
                       :src="item.icon">
                </image>
                <text class="">{{item.name}}</text>
              </view>
              <image class=""
                     v-if="AiModel === item.aiModel"
                     style="width: 26rpx;height: 23rpx;"
                     src="/static/aiCreate/btn_selected.png">
              </image>
            </view>
          </view>
          <view class="zl-flex zl-row-between"
                style="border-top: 1rpx solid #e5e5e5;padding:30rpx;">
            <view style="background-color:#000;width: 64rpx;height: 64rpx;margin-right: 30rpx;border-radius: 18rpx;display:flex;justify-content:center;align-items:center;"
                  @click="openType(item)">
              <image :src="imageSrc"
                     style="width: 44rpx;height: 44rpx;"
                     mode="scaleToFill" />
            </view>
            <textarea auto-height="true"
                      @input="changeInput"
                      @confirm="getWss"
                      confirm-type="send"
                      v-model="TEXT"
                      cursor-spacing="160"
                      placeholder="写下你想问的..."
                      maxlength="9000" />
            <image src="/static/aiCreate/btn_fabu.png"
                   @click="getWss"
                   style="width: 48rpx;height: 48rpx;"
                   mode="scaleToFill" />
          </view>
        </view>
      </view>
    </view>

    <!-- <u-picker mode="selector"
              v-model="show"
              z-index="999"
              :default-selector="[0]"
              :range="selectorObj"
              range-key="name"></u-picker>
    <picker mode="selector"
            :value="index"
            :range="selectorObj"
            range-key="name">
      <view class="uni-input">{{selectorObj[index].name||'请选择'}}</view>
    </picker> -->
  </view>
</template>

<script>
import ChatList from "@/components/chat_list.vue";
export default {
  data () {
    return {
      tempMsg: null,
      scrollY: 99999,
      loadingData: false,
      loading: false,
      topTabh: 0,
      TEXT: '',
      historyTextList: [], // 历史会话信息，由于最大token12000,可以结合实际使用，进行移出
      tempRes: '', // 临时答复保存
      lock: false, // 锁定
      balanceInfo: {},
      storeInfo: {},
      selectorObj: [],
      AiModel: 0,
      show: false,
      index: 0,

      isShow: false,
      imageSrc: '',
      AiModelName: ''
    }
  },
  onLoad (options) {
    const systemInfo = uni.getSystemInfoSync();
    this.topTabh = systemInfo.statusBarHeight * 2 + 84;
    this.getassetamount()
    this.getmodel()
  },
  onNavigationBarButtonTap (e) {
    uni.navigateTo({
      url: '/pages/ai_chat_record/ai_chat_record'
    })
  },
  components: {
    ChatList
  },
  onBackPress (options) {
    uni.$emit('updateUser')
  },
  methods: {
    openType (item) {
      this.isShow = !this.isShow
    },
    bindPickerChange (e) {
      if (e.aiModel === 1) {
        this.imageSrc = '/static/aiCreate/icon_model_white_01.png'
      } else if (e.aiModel === 2) {
        this.imageSrc = '/static/aiCreate/icon_model_white_02.png'
      } else if (e.aiModel === 3) {
        this.imageSrc = '/static/aiCreate/icon_model_white_03.png'
      }
      uni.setNavigationBarTitle({
        title: e.name
      });
      this.AiModel = e.aiModel
      this.AiModelName = e.name
      this.isShow = false
    },
    getmodel () {
      this.api.aichat.getmodel().then(res => {
        if (res.code === 0) {
          this.selectorObj = res.data
          this.AiModelName = this.selectorObj[0].name
          if (this.selectorObj[0].aiModel === 1) {
            this.imageSrc = '/static/aiCreate/icon_model_white_01.png'
          } else if (this.selectorObj[0].aiModel === 2) {
            this.imageSrc = '/static/aiCreate/icon_model_white_02.png'
          } else if (this.selectorObj[0].aiModel === 3) {
            this.imageSrc = '/static/aiCreate/icon_model_white_03.png'
          }
          uni.setNavigationBarTitle({
            title: this.selectorObj[0].name
          });
          this.AiModel = this.selectorObj[0].aiModel
        } else {
          this.$util.msg(res.msg);
        }
      }).catch(err => {
        this.$util.msg('请检查网络连接！');
      })
    },
    goBack () {
      uni.navigateBack()
    },
    refsh (d) {
      if (this.lock) {
        return this.utils.toast('请等待上个问题回答完成');
      }

      this.text = d.messageText
      this.getWss()
    },
    changeInput () {
      if (this.TEXT.indexOf('\n') > -1) {
        this.TEXT = this.TEXT.replaceAll('\n', '')
      }
    },
    async sendToSpark () {
      if (this.TEXT === '') {
        return uni.showToast({
          title: '请输入内容',
          icon: 'none'
        })
      }
      if (this.lock) {
        return uni.showToast({
          title: '请等待上个问题回答完成',
          icon: 'none'
        })
      }
      this.historyTextList.push({
        content: this.TEXT,
        role: 'user'
      })

      this.lock = true
      this.tempRes = "";
      let par = {
        AiModel: this.AiModel,
        sessionId: this.sessionId ? this.sessionId : '',
        templateId: 0,
        question: this.TEXT,
      }
      // uni.showLoading({
      //   title: 'ai助手回答中'
      // });
      this.loading = true
      this.api.aichat.qwenAll(par).then(res => {
        // uni.hideLoading();
        if (res.code === 0) {
          this.sessionId = res.data.sessionId;
          this.historyTextList.push({
            content: res.data.answer,
            reasoning_content: res.data.reasoning_content,
            role: 'assistant'
          })
          this.$nextTick(() => {
            uni.pageScrollTo({
              scrollTop: 8000000000, //滚动到页面的目标位置（单位px）
              duration: 200 //滚动动画的时长，默认300ms，单位 ms
            })
          });
          this.lock = false
          this.loading = false
          this.TEXT = ''
        } else {
          this.loading = false
          this.lock = false
          this.$util.msg(res.msg);
        }
      }).catch(err => {
        this.loading = false
        this.$util.msg('请检查网络连接！');
      })
    },
    // 获取账号资源总计
    getassetamount () {
      this.api.account.getassetamount().then(res => {
        if (res.code === 0) {
          this.balanceInfo = res.data;
        } else {
          this.$util.msg(res.msg);
        }
      }).catch(err => {
        this.$util.msg(err);
        // this.$util.msg('请检查网络连接！');
      })
    },
    // getuserInfo () {

    //   this.$u.api.accoutDetail({
    //     id: this.storeInfo.accountID
    //   }).then(res => {

    //     if (res.flag) {
    //       // console.log(res.data);
    //       this.storeInfo = res.data
    //       // console.log(this.storeInfo);
    //       uni.setStorageSync('storeInfo', res.data);

    //     } else {
    //       this.$util.msg(res.msg)
    //     }
    //     this.showView = true;
    //   }).catch(err => {
    //     console.log(err, '报错');
    //     this.$util.msg('请检查网络连接！');
    //     // uni.reLaunch({
    //     // 	url: '/pages/login/login'
    //     // })
    //   })
    // },
    // 鉴权
    getWss () {
      if (!this.balanceInfo.endTime) {
        return this.$util.msg('会员已到期,请续费')
      }
      this.sendToSpark()
    },

  }
}
</script>


<style scoped lang="scss">
.top-box {
  background-color: #763ac9;
  position: relative;

  .top {
    position: absolute;
    bottom: 0;
    left: 0;
    height: 84upx;
    padding: 0 30upx;
    z-index: 9999;

    .backIcon {
      width: 20upx;
      height: 35upx;
    }

    .top-title {
      width: 380rpx;
    }

    .btn {
      width: 155rpx;
      height: 50rpx;

      image {
        width: 30rpx;
        height: 30rpx;
      }
    }
  }
}

.chat-con {
  display: flex;
  flex-direction: column;
  height: 100%;

  & > view {
    &:nth-child(1) {
      // flex: 1;
      // width: 100vw;
      // overflow: hidden;
    }

    &:nth-child(2) {
      position: fixed;
      bottom: 0rpx;
      left: 0;
      display: flex;
      align-items: center;
      width: 100vw;
      // height: 128rpx;
      padding: 0 0 30rpx;
      background: #ffffff;

      & > view {
        // height: 87rpx;

        margin: 0 auto 20rpx;
        // padding-left: 20rpx;
        // padding-right: 20rpx;
        border-radius: 40rpx !important;
        overflow: hidden;
        // border: 1rpx solid #567aed;

        &:nth-child(1) {
          flex: 1;

          input {
            padding-top: 20rpx;
            padding-bottom: 20rpx;
            width: 100%;
          }

          textarea {
            padding: 20rpx 0;
            width: 88%;
          }
        }

        &:nth-child(2) {
          display: flex;
          align-items: center;
          justify-content: center;
          padding-left: 10rpx;

          text {
            color: #aabcf6;
            font-size: 38rpx;
          }
        }
      }
    }
  }
}

.group-btn {
  font-size: 36rpx;
  color: #101012;
}

.cate-con {
  padding: 25rpx;

  & > view {
    &:nth-child(1) {
      height: 96rpx;
      background: #ffffff;
      border-radius: 10rpx;
      border: 1rpx solid #d4d4d4;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: #101012;
    }

    &:nth-child(2) {
      margin-top: 30rpx;

      & > view {
        display: flex;
        height: 76rpx;
        border-radius: 10rpx;
        border: 1rpx solid #d4d4d4;
        align-items: center;
        padding-left: 22rpx;
        padding-right: 20rpx;
        margin-bottom: 20rpx;

        &.active {
          background: #f8faff;
          border: 1rpx solid #577bed;
          color: #577bed;
        }

        & > view {
          &:nth-child(1) {
            text {
              font-size: 28rpx;
            }
          }

          &:nth-child(2) {
            // @include textOverflow();
            flex: 1;
            margin-left: 14rpx;
            margin-right: 14rpx;
          }

          &:nth-child(3) {
            text {
              font-size: 26rpx;
            }
          }
        }
      }
    }
  }
}

.add-cate-inp {
  padding: 40rpx 30rpx;

  input {
    height: 84rpx;
    line-height: 84rpx;
    background: #f6f6f6;
    border-radius: 20rpx;
    padding-left: 20rpx;
    padding-right: 20rpx;
  }
}
</style>